<template>
    <div class="page-container">
        <TableHead
            :config="tableHeaderConfig"
            :searchdata.sync="filters"
            v-show="showSearch"
            @parentPageList="findPageList"
        ></TableHead>
        <!--表格内容栏-->
        <el-card class="card-box">
            <table-tool-bar :showSearch.sync="showSearch" @queryTable="findPageList" :columns="columns">
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">新增</el-button>
            </table-tool-bar>
            <Table
                v-model="filters.pageNum"
                :columns="columns"
                :data="tableList"
                :total="total"
                :loading="loading"
                showNo
                @getPageList="findPageList"
            >
                <template slot="triggerState" slot-scope="{ scope }">
                    <el-tag v-if="scope.row.triggerState === 'BLOCKED'" size="small" type="warning">阻塞</el-tag>
                    <el-tag v-if="scope.row.triggerState === 'COMPLETE'" size="small" type="success">完成</el-tag>
                    <el-tag v-if="scope.row.triggerState === 'ERROR'" size="small" type="danger">错误</el-tag>
                    <el-tag v-if="scope.row.triggerState === 'PAUSED'" size="small" type="info">暂停</el-tag>
                    <el-tag v-if="scope.row.triggerState === 'WAITING'" size="small" type="primary">等待</el-tag>
                    <el-tag v-if="scope.row.triggerState === 'PAUSED_BLOCKED'" size="small">暂停阻塞</el-tag>
                </template>
                <template slot="requestsRecovery" slot-scope="{ scope }">
                    <el-tag v-if="scope.row.requestsRecovery == 0" size="small" type="danger">否</el-tag>
                    <el-tag v-if="scope.row.requestsRecovery == 1" size="small" type="success">是</el-tag>
                </template>
                <template slot="oper" slot-scope="{ scope }">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </Table>
        </el-card>
        <!--新增与编辑的弹窗-->
        <EditItem
            v-model="dialogVisible"
            :data-form="dataForm"
            :dialog-config="dialogConfig"
            :data-form-rules="dataFormRules"
            :dialog-tag="dialogTag"
            :title="title"
            width="600px"
            @submitForm="submitForm"
        >
            <el-popover v-model="cronPopover" slot="cronExpression">
                <el-input
                    slot="reference"
                    @click="cronPopover = true"
                    v-model="dataForm.cronExpression"
                    placeholder="请输入定时策略"
                ></el-input>
                <cron @change="changeCron" @close="cronPopover = false"></cron>
            </el-popover>
        </EditItem>
    </div>
</template>

<script>
import TableHead from '@/components/TableHeadSearch'
import TableToolBar from '@/components/TableToolBar'
import EditItem from '@/components/EditItem'
import { cron } from 'vue-cron'
import { getTriggersList, addTrigger, editTrigger, deleteTrigger } from '@/api/task/index'

import { confirm } from '@/utils/utils'

export default {
    name: 'triggers',
    components: {
        TableHead,
        EditItem,
        TableToolBar,
        cron
    },
    data() {
        const isJsonStr = (rule, str, cb) => {
            try {
                if (!str) {
                    return cb()
                }
                var obj = JSON.parse(str)
                return cb()
            } catch (e) {
                cb(new Error('请输入json格式'))
            }
        }
        return {
            title: '新增触发器',
            showSearch: true,
            cronPopover: false,
            // 表格要查询的字段配置
            filters: {
                jobGroup: '',
                jobName: '',
                triggerName: '',
                triggerGroup: '',
                triggerState: '',
                startTime: '',
                endTime: '',
                pageNum: 1,
                pageSize: 10
            },
            loading: false,
            // 表格搜索处的字段
            tableHeaderConfig: [
                { title: '触发器名称', code: 'triggerName', type: 'input' },
                { title: '触发器组', code: 'triggerGroup', type: 'input' },
                {
                    title: '触发器状态',
                    code: 'triggerState',
                    type: 'select',
                    options: [
                        { label: '阻塞', value: 'BLOCKED' },
                        { label: '完成', value: 'COMPLETE' },
                        { label: '错误', value: 'ERROR' },
                        { label: '暂停', value: 'PAUSED' },
                        { label: '等待', value: 'WAITING' },
                        { label: '暂停阻塞', value: 'PAUSED_BLOCKED' }
                    ]
                },

                { title: '任务名称', code: 'jobName', type: 'input' },
                { title: '任务分组', code: 'jobGroup', type: 'input' },
                { title: '起止时间', code: 'createtime', type: 'datetimerange' }
            ],
            // 列表的列的展示字段
            columns: [
                { prop: 'triggerName', label: '触发器名称', visible: true, key: 'triggerName' },
                { prop: 'triggerGroup', label: '触发器分组', visible: true, key: 'triggerGroup' },
                { prop: 'triggerType', label: '触发器类型', visible: true, key: 'triggerType' },
                { slot: 'triggerState', label: '触发器状态', visible: true, key: 'triggerState' },
                { prop: 'startTime', label: '开始时间', type: 'formatTime', visible: true, key: 'startTime' },
                { prop: 'endTime', label: '结束时间', type: 'formatTime', visible: true, key: 'endTime' },
                { prop: 'prevFireTime', label: '上次执行时间', type: 'formatTime', visible: true, key: 'prevFireTime' },
                { prop: 'nextFireTime', label: '下次执行时间', type: 'formatTime', visible: true, key: 'nextFireTime' },
                { prop: 'jobName', label: '任务名称', visible: true, key: 'jobName' },
                { prop: 'jobGroup', label: '任务分组', visible: true, key: 'jobGroup' },
                {
                    prop: 'description',
                    label: '描述',
                    width: 200,
                    showOverflowTooltip: true,
                    visible: true,
                    key: 'description'
                },
                {
                    slot: 'oper',
                    label: '操作',
                    align: 'center',
                    minWidth: 120,
                    fixed: 'right',
                    visible: true,
                    key: 'oper'
                }
            ],
            // 接口返回data
            tableList: [],
            total: 0,
            // 新增编辑界面是否显示
            dialogVisible: false,
            // 规则
            dataFormRules: {
                jobName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
                jobGroup: [{ required: true, message: '请输入任务分组', trigger: 'blur' }],
                triggerName: [{ required: true, message: '请输入触发器名称', trigger: 'blur' }],
                triggerGroup: [{ required: true, message: '请输入触发器分组', trigger: 'blur' }],
                triggerType: [{ required: true, message: '请选择触发器类型', trigger: 'change' }],
                triggerParamMap: [{ message: '触发器参数必须为json串', validator: isJsonStr, trigger: 'blur' }]
            },
            // 新增编辑界面数据
            dataFormDefault: {
                triggerName: '',
                triggerGroup: '',
                cronExpression: '',
                jobName: '',
                jobGroup: '',
                misfire: '',
                priority: 0,
                triggerDescription: '',
                triggerParamMap: '',
                triggerType: '',
                startTime: '',
                endTime: ''
            },
            dataForm: {},
            // dialog 要渲染的数据json
            dialogConfig: [
                { title: '任务名称', code: 'jobName', type: 'input', maxlength: 50, disabled: 'edit' },
                { title: '任务分组', code: 'jobGroup', type: 'input', maxlength: 200, disabled: 'edit' },

                { title: '触发器名称', code: 'triggerName', type: 'input', maxlength: 50 },
                { title: '触发器分组', code: 'triggerGroup', type: 'input', maxlength: 200 },

                { title: 'CRON表达式', slot: 'cronExpression' },

                {
                    title: '触发器类型',
                    code: 'triggerType',
                    type: 'select',
                    options: [
                        { value: 'CALENDAR', label: 'CALENDAR' },
                        { value: 'CRON', label: 'CRON' },
                        { value: 'SIMPLE', label: 'SIMPLE' }
                    ]
                },
                { title: '开始时间', code: 'startTime', type: 'datetime' },
                { title: '结束时间', code: 'endTime', type: 'datetime' },
                // { title: '结束时间', code: 'endTime', type: 'datetime' },
                // { title: '起止时间', code: 'startAndEndTime', type: 'datetimerange' },
                {
                    title: '描述',
                    code: 'triggerDescription',
                    type: 'textarea',
                    maxlength: 200
                },
                {
                    title: '触发器参数',
                    code: 'triggerParamMap',
                    type: 'textarea',
                    placeholder: '请输入json格式,如{"a":1,"b":"abc"}',
                    maxlength: 200
                }
            ],
            dialogTag: '' // 编辑与新样的标识
        }
    },
    mounted() {},
    created() {
        this.findPageList()
    },
    methods: {
        changeCron(val) {
            this.dataForm.cronExpression = val
        },
        // 获取分页数据
        findPageList() {
            this.loading = true
            getTriggersList(this.filters)
                .then((res) => {
                    this.tableList = res.data.items
                    this.total = res.data.total
                })
                .finally(() => {
                    this.loading = false
                })
        },
        // 删除
        handleDelete(row) {
            confirm('确定要删除吗?').then(() => {
                deleteTrigger({ triggerGroup: row.triggerGroup, triggerName: row.triggerGroup }).then((res) => {
                    this.$message.success('删除成功')
                    this.findPageList()
                })
            })
        },
        // 显示新增界面
        handleAdd() {
            this.dialogVisible = true
            this.dataForm = Object.assign({}, this.dataFormDefault)
            this.dialogTag = 'add'
        },
        // 显示编辑界面
        handleEdit(params) {
            this.title = '编辑触发器'
            this.dialogVisible = true
            this.dataForm = Object.assign({}, params)
            console.log(new Date(params.startTime).toLocaleString().replace(/:\d{1,2}$/, ' '))
            // this.dataForm.startTime = Date.parse(new Date(params.startTime))
            // this.dataForm.startAndEndTime = [params.startTime, params.endTime]
            this.dialogTag = 'edit'
        },
        // 编辑与新增 提交 请求接口
        submitForm(data) {
            let fetchApi = this.dialogTag === 'add' ? addTrigger : editTrigger
            fetchApi(data).then((res) => {
                this.$message.success(res.msg)
                this.findPageList()
                this.dataForm = Object.assign({}, this.dataFormDefault)
                this.dialogVisible = false
            })
        }
    }
}
</script>
<style scoped></style>
